package com.masterclient.app.businessmodule.settingmodule.bankcard;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.settingmodule.bankcard.bean.NewBankBean;
import com.masterclient.app.businessmodule.settingmodule.bankcard.bean.NewBankCardBean;
import com.masterclient.app.businessmodule.settingmodule.bankcard.contract.BankCardManageContract;
import com.masterclient.app.businessmodule.settingmodule.bankcard.contract.BankCardManagePresenter;
import com.masterclient.app.utils.CaptchaUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;


public class BankCardInsertActivity extends FCBusinessActivity<BankCardManagePresenter> implements BankCardManageContract.View,TextWatcher{

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.card_id)
    TextView card_id;
    @BindView(R.id.bank_name)
    TextView bank_name;
    @BindView(R.id.bankcard_number)
    EditText bankcard_number;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.et_verify)
    EditText et_verify;
    @BindView(R.id.confirm_submit)
    TextView confirm_submit;
    @BindView(R.id.tv_get_yan)
    TextView tv_get_yan;

    NewBankCardBean bankCardData;
    String id_number = "";
    String type = "1";

    CaptchaUtil captchaUtil;


    @Override
    protected int requireGetLayoutId() {
        return R.layout.bank_card_bind;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("添加银行卡");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#FFFFFF"));

        name.setText(UserDataManager.getInstance().getIdCardRealName());
        card_id.setText(UserDataManager.getInstance().getIdCardNo());

        bankCardData = (NewBankCardBean) getIntent().getSerializableExtra("bankCardData");
        if(bankCardData != null){
            type = "0";
//            name.setText(bankCardData.getSh_real_name());
//            card_id.setText(bankCardData.getSh_id_number());
            bank_name.setText(bankCardData.bankcard.bankName);
            //bankcard_number.setText(bankCardData.getSh_card_number());
            //phone.setText(bankCardData.getSh_bank_mobile());
            bank_code = bankCardData.bankcard.bankCode;
            id_number = bankCardData.bankcard.bankcardCertificationId;
            //confirm_submit.setText("保存银行卡");
            set_submit_clickable();
        }
        mPresenter.getBank();


        captchaUtil = new CaptchaUtil(mContext,"绑定银行卡");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                tv_get_yan.setClickable(false);
                mPresenter.getCaptcha(phone.getText().toString().trim(), "bind_card", ne);
            }

            @Override
            public void onFailed() {
                tv_get_yan.setClickable(true);
            }
        });

        addListener();
    }

    private void addListener() {

        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                if (charSequence.equals(" "))
                    return "";
                return null;
            }
        };

        name.addTextChangedListener(this);
        name.setFilters(new InputFilter[]{inputFilter});
        card_id.addTextChangedListener(this);
        card_id.setFilters(new InputFilter[]{inputFilter});
        card_id.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] aa = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
                return aa;
            }

            @Override
            protected char[] getReplacement() {
                char[] cc = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
                return cc;
            }
        });
        bankcard_number.addTextChangedListener(this);
        phone.addTextChangedListener(this);
        et_verify.addTextChangedListener(this);
    }

    private boolean canSubmit() {


        boolean nameFlag = !TextUtils.isEmpty(name.getText().toString().trim());
        boolean phoneFlag = !TextUtils.isEmpty(phone.getText().toString().trim());
        boolean idFlag = !TextUtils.isEmpty(card_id.getText().toString().trim());
        boolean bankCardFlag = !TextUtils.isEmpty(bankcard_number.getText().toString().trim());
        boolean bankFlag = !TextUtils.isEmpty(bank_code);
        boolean verifyFlag = !TextUtils.isEmpty(et_verify.getText().toString().trim());

        return nameFlag && phoneFlag && idFlag && bankCardFlag && bankFlag & verifyFlag;

    }

    public boolean isMobileNum(String phoneNum) {
//        Pattern p = Pattern
//                .compile("^((13[0-9])|(15[0-9])|(16[0-9])|(19[0-9])|(17[0-9])|(18[0-9])|(14[0-9]))\\d{8}$");
        Pattern p = Pattern
                .compile("^((1[0-9]))\\d{9}$");
        return p.matcher(phoneNum).matches();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 103:

                break;
            case 104:

                break;
        }
    }

    @OnClick({R.id.confirm_submit,R.id.bank_name,R.id.tv_get_yan})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm_submit:

                String real_name = name.getText().toString().trim();
                String card_number = bankcard_number.getText().toString().trim();
                String bank_tel = phone.getText().toString();
                String captcha = et_verify.getText().toString().trim();

                if(!canSubmit()){
                    return;
                }

//                if(TextUtils.isEmpty(real_name)){
//                    showToast("请输入真实姓名");
//                    return;
//                }
//                if(TextUtils.isEmpty(id_number)){
//                    showToast("身份证号码格式不正确");
//                    return;
//                }

                if(TextUtils.isEmpty(bank_code)){
                    showToast("请选择所属银行");
                    return;
                }

//                if(!isBankCard(card_number)){
//                    showToast("银行卡格式不正确");
//                    return;
//                }

                if(!isMobileNum(bank_tel)){
                    showToast("手机号码格式不正确");
                    return;
                }

                mPresenter.bankManage(real_name,id_number,card_number,bank_code,bank_tel,type,captcha);

                break;
        case R.id.bank_name:
            OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                    //返回的分别是三个级别的选中位置
                    selected = banks.get(options1);
                    bank_code = selected.code;
                    bank_name.setText(selected.shortName);
                    set_submit_clickable();
                }
            }).setOutSideCancelable(false)//点击外部dismiss default true
                    .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                    .setSubmitColor(Color.parseColor("#d9000000"))//确定按钮文字颜色
                    .setCancelColor(Color.parseColor("#80000000"))//取消按钮文字颜色
                    .setTitleBgColor(0xFFFFFFFF)//标题背景颜色 Night mode
                    .setLineSpacingMultiplier(2.5f)//行间距
                    .setDividerColor(Color.parseColor("#00FFFFFF"))//设置分割线的颜色
                    .build();
            pvOptions.setPicker(banks);
            pvOptions.setTitleText("选择所属银行");

            int select = 0;
            for(int i = 0; i < banks.size(); i ++){
                if(banks.get(i).code.equals(bank_code)){
                    select = i;
                }
            }
            pvOptions.setSelectOptions(select);
            pvOptions.show();

                break;
            case R.id.tv_get_yan:
                if(TextUtils.isEmpty(phone.getText().toString().trim())){
                    showToast("输入银行预留的手机号");
                    return;
                }
                if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
                        mPresenter.getCaptcha(phone.getText().toString().trim(), "bind_card", "");
                    }else {
                        captchaUtil.start();
                    }
                } else {
                    tv_get_yan.setClickable(false);
                    mPresenter.getCaptcha(phone.getText().toString().trim(), "bind_card", "");
                }
                break;
        }
    }

    private boolean isBankCard(String card_number) {
        return card_number.length() > 12 && card_number.length() < 20 && card_number.startsWith("62") ;
    }


    List<NewBankBean.BankItemBean> banks = new ArrayList<>();
    NewBankBean.BankItemBean selected = null;
    String bank_code = "";
    @Override
    public void getBankSuccess(NewBankBean data) {
        if(data != null && data.banks != null){
            banks.clear();
            banks.addAll(data.banks);
        }
    }

    @Override
    public void getBankFailed(String msg) {

    }

    @Override
    public void BankManageSuccess() {
        showToast("验证成功，银行卡已成功绑定");
        setResult(2);
        finish();

    }

    @Override
    public void BankManageFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void showBankCard(NewBankCardBean data) {

    }

    @Override
    public void getBankCardFail(String msg) {

    }

    @Override
    public void BankRemoveSuccess() {

    }

    @Override
    public void BankRemoveFailed(String msg) {

    }

    CountDownTimer timer;
    @Override
    public void getCaptchaSuccess() {
        tv_get_yan.setBackgroundResource(R.drawable.bg_gray_coner);
        tv_get_yan.setTextColor(0xffc1c1c1);
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_get_yan.setText(millisUntilFinished / 1000 + "s");
                tv_get_yan.setTextColor(0x4d000000);
                tv_get_yan.setBackgroundResource(R.drawable.withdraw_get_code_bkg);
            }

            @Override
            public void onFinish() {
                tv_get_yan.setClickable(true);
                tv_get_yan.setTextColor(0xff7399E5);
                tv_get_yan.setBackground(null);
                tv_get_yan.setText("获取验证码");
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void getCaptchaFailed() {

    }

    @Override
    public void getCaptchaFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        set_submit_clickable();
    }

    private void set_submit_clickable() {
        if(canSubmit()){
            confirm_submit.setBackgroundResource(R.drawable.shape_round_f23051);
            confirm_submit.setTextColor(Color.parseColor("#FFFFFF"));
        }else{
            confirm_submit.setBackgroundResource(R.drawable.bankcard_bind_unable_click_bkg);
            confirm_submit.setTextColor(Color.parseColor("#FFE0E0"));
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }


    //点击空白区域，软键盘消失
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(getApplicationContext(), v.getWindowToken());
            }

            // 判断连续点击事件时间差
            if (isFastClick()) {
                return true;
            }

        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    public static void hideSoftInput(Context context, IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }


    private static final int MIN_DELAY_TIME = 300;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

}
